<?php
/**
 * Created by PhpStorm.
 * User: hisheng
 * Date: 2017/6/5
 * Time: 16:35
 */
namespace App\Http\Controllers;

use App\Loan;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Input;

class LoanController extends Controller
{
    public $loan;
    public function __construct(Loan $loan)
    {
        $this->loan = $loan;
    }
    
    //贷款列表页
    public function index(){
        $loans = Loan::orderBy('updated_at','desc')->get();
        var_dump($loans->toArray());
        return view('loan.index');
    }
    //增加页面
    public function add(){
        return view('loan.add');
    }
    
    public function postAdd(){
        $this->insertDefault('company_name');
        $this->insertDefault('loan_url');
        $this->insertDefault('provision');
        $this->insertDefault('apply');
        $this->insertDefault('feature');
        $this->insertDefault('min_amount');
        $this->insertDefault('max_amount');
        $this->insertDefault('min_days');
        $this->insertDefault('max_days');
        $this->insertDefault('name');
        $this->insertDefault('rate');
        $this->insertDefault('rate_type');
        $this->insertDefault('job');
        $this->insertDefault('success_rate');
        $this->insertFile('icon');
        $this->insertMonthRate();
        $this->loan->save();
        return redirect('/loans');
    }
    
    public function insertMonthRate(){
        $rate_type = $this->loan->rate_type;
        if(empty($rate_type)){
            throw new \Exception('缺少rate_type');
        }
        $month_rate = '';
        if($rate_type == 'day'){
            $month_rate = $this->loan->rate * 30;
        }
        if($rate_type == 'month'){
            $month_rate = $this->loan->rate ;
        }
        
        if($month_rate){
            $this->loan->month_rate = $month_rate;
        }
        
        
    }
    
    public function insertDefault($name){
        $v = Input::get($name);
        if($name){
            $this->loan->$name = $v;
        }
    }
    public function insertFile($name){
        $avatar = $this->saveFile($name);
        if($avatar){
            $this->loan->icon = $avatar;
        }
    }
    
    public function saveFile($name){
        $file = Input::file($name);
        if ($file) {
            $avatar = $this->saveToPublicUploadTmp($file);
            return $avatar;
        }
    }
    
    //**  保存到本地 upload_tmp 并返回图片地址
    public function saveToPublicUploadTmp(UploadedFile $file){
        $destinationPath = 'assets';
        $par = "/[\x80-\xff]/";
        $filename = $file->getClientOriginalName();
        $filename = preg_replace($par,"",$filename);
        $file->move($destinationPath, $filename);
        $avatar = './assets/'.$filename; //取图片的时候用到
        $avatarNmae = 'assets/'.$filename;
        return $avatarNmae;
    }
    
    
}